package com.itheima.action;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;
import javax.ws.rs.core.MediaType;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Controller;

import com.itheima.utils.BaseAction;
import com.itheima.utils.MailUtils;

import cn.itcast.crm.domain.Customer;
import itcast.bos.domain.finaldemo.FinalDemo;

@Controller
@ParentPackage("json-default")
@Namespace("/")
@Scope("prototype")
public class CustomerAction extends BaseAction<Customer> {

	private String checkcode;

	@Autowired
	private JmsTemplate jt;

	@Autowired
	private RedisTemplate<String, String> redisTemplate;

	private String activeCode;

	// 4客户登录功能
	@Action(value = "customerLogin", results = {
			@Result(name = "success", type = "redirect", location = "index.html#/myhome"),
			@Result(name = "login", type = "redirect", location = "login.html") })
	public String login() {
		Customer c = WebClient
				.create(FinalDemo.Crm_Manager_Url + "/crm_management/services/customerService/customerLogin?telephone="
						+ model.getTelephone() + "&password=" + model.getPassword())
				.get(Customer.class);
		System.out.println("查找出来的客户信息-----------------------------------------"+c);
		if (c != null) {
			ServletActionContext.getRequest().getSession().setAttribute("customer", c);
			return SUCCESS;
		}
		return "login";
	}

	// 3激活邮件的action
	@Action(value = "customer_activeMail", results = {
			@Result(name = "success", type = "redirect", location = "signup-success.html"),
			@Result(name = "input", type = "redirect", location = "signup.html") })
	public String active() throws IOException {
		ServletActionContext.getResponse().setContentType("text/html;charset=UTF-8");
		String resCode = redisTemplate.opsForValue().get(model.getTelephone());
		if (resCode == null || !resCode.equals(activeCode)) {
			System.out.println("電話號碼  注冊========" + model.getTelephone());
			Customer c = WebClient
					.create("http://localhost:9995/crm_management/services/customerService/findByTelephone/"
							+ model.getTelephone())
					.accept(MediaType.APPLICATION_JSON).get(Customer.class);
			System.out.println("客戶======" + c);
			if (c.getType() == null || c.getType() != 1) {
				WebClient.create("http://localhost:9995/crm_management/services/customerService/bindEmils/"
						+ model.getTelephone()).accept(MediaType.APPLICATION_JSON).get();
				ServletActionContext.getResponse().getWriter().println("邮箱绑定成功！");
			}
		} else {
			ServletActionContext.getResponse().getWriter().println("验证码失效，请重新登录系统进行操作");

		}
		redisTemplate.delete(model.getTelephone());
		return NONE;
	}

	// 2注册用户
	@Action(value = "customer_regist", results = {
			@Result(name = "success", type = "redirect", location = "signup-success.html"),
			@Result(name = "input", type = "redirect", location = "signup.html") })
	public String customerRegist() throws IOException {
		// 拿到随机的验证码
		String code = (String) ServletActionContext.getRequest().getSession().getAttribute(model.getTelephone());
		if (code == null || !code.equals(checkcode)) {
			System.out.println("验证码出错。。。");
			return INPUT;
		}
		WebClient.create("http://localhost:9995/crm_management/services/customerService/addCustomer")
				.type(MediaType.APPLICATION_JSON).post(model);
		System.out.println("注册成功。。。");
		// 发送邮件
		String activeCode = RandomStringUtils.randomNumeric(32);
		redisTemplate.opsForValue().set(model.getTelephone(), activeCode, 24, TimeUnit.HOURS);
		String content = "尊重的客户您好，轻语24小时内激活，地址：<br /><a href='" + MailUtils.activeUrl + "?telephone="
				+ model.getTelephone() + "&activeCode=" + activeCode + "'>激活操作</a>";
		MailUtils.sendMail("速运激活邮件", content, model.getEmail());
		return SUCCESS;
	}

	// 1发送短信
	@Action(value = "customer_sendSms")
	public String sendMaseage() throws IOException {
		String randomCode = RandomStringUtils.randomNumeric(4);
		System.out.println("电话号码：" + model.getTelephone() + "验证码：" + randomCode);
		ServletActionContext.getRequest().getSession().setAttribute(model.getTelephone(), randomCode);

		final String msg = "亲爱的顾客，您的验证码是：" + randomCode + ".服务热线：测试。。。";
		jt.send("bos_msg", new MessageCreator() {

			@Override
			public Message createMessage(Session session) throws JMSException {
				MapMessage m = session.createMapMessage();
				m.setString("telephone", model.getTelephone());
				m.setString("msg", msg);
				return m;
			}
		});

		/*
		 * String result = SmsUtils.sendSmsByHTTP(model.getTelephone(), msg);
		 */
		String result = "000/123465";
		if (result.startsWith("000")) {
			return NONE;
		} else {
			throw new RuntimeException("消息发送失败，失败码：" + result);
		}

	}

	public String getCheckcode() {
		return checkcode;
	}

	public void setCheckcode(String checkcode) {
		this.checkcode = checkcode;
	}

}
